<template>
    <div class="login_box">
        <el-form class='login_form' :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" prefix-icon="el-icon-lock"></el-input>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="info" @click="resetLoginForm">重置</el-button>
            </el-form-item>
        </el-form>    
    </div>
</template>

<script>
import { reactive, ref, toRefs } from '@vue/reactivity';
import router from '../router';
import {ElMessage} from "element-plus";
function useLogin(loginFormRef,state){
    const login=()=>{
        loginFormRef.value.validate((valid)=>{
            console.log('logining' + valid);

            const params ={username: state.loginForm.username,
                           password: state.loginForm.password};
            console.log(JSON.stringify(params));
            console.log("use axios pass user and passworkd")
            //如果成功，可以保存token，未来接口访问可以带上token
            ElMessage.success("login success");
            window.sessionStorage.setItem('token', "response.data.token vaule");
            router.push("/");
        })
    };
    return {
        login
    }
}

function useRestLog(loginFormRef){
    const resetLoginForm=()=>{
        loginFormRef.value.resetFields();
    };
    return {
        resetLoginForm
    }
}

export default{
    setup(){
        const state = reactive({
            loginForm:{
                username:'',
                password:''
            },
        });

        const loginFormRef = ref();

        const loginFormRules={
            username:[{required: true, message:'输入用户名', trigger:'blur'},{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
            password:[{required: true, message:'输入密码', trigger:'blur'},{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }]
        };

        return {
            ...toRefs(state),
            loginFormRules,
            loginFormRef,
            ...useRestLog(loginFormRef),
            ...useLogin(loginFormRef,state)
        }
    }
}
</script>

<style>
.login_form{
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
}
.login_box{
    width: 450px;
    height: 300px;
    background-color: rgb(255, 255, 255);
    border-radius: 3px;
    margin: 0 auto;
}
</style>
